import { _decorator, CCInteger, Collider2D, Color, Component, EventTouch, Graphics, IPhysics2DContact, Node, UITransform, v2 } from 'cc';
import { Item } from '../Item';
const { ccclass, property } = _decorator;

@ccclass('Chalk')
export class Chalk extends Item {

    @property(Color)
    paintColor: Color = null;

    @property(CCInteger)
    paintWidth: number = 3;

    graphics: Graphics;

    isIn = false;

    TouchMove(event: EventTouch): void {
        if (this.isTween) return;
        super.TouchMove(event);
        if (this.graphics) {
            if (this.graphics.getComponent(UITransform).getBoundingBoxToWorld().contains(v2(this.node.getWorldPosition().x, this.node.getWorldPosition().y))) {
                let pos = this.graphics.getComponent(UITransform).convertToNodeSpaceAR(this.node.getWorldPosition());
                if (!this.isIn) {
                    this.isIn = true;
                    this.graphics.lineWidth = this.paintWidth;
                    this.graphics.moveTo(pos.x, pos.y);
                }
                this.graphics.strokeColor = this.paintColor;
                this.graphics.lineTo(pos.x, pos.y);
                this.graphics.stroke();
                this.graphics.moveTo(pos.x, pos.y);
            }
            else this.isIn = false;
        }
        else this.isIn = false;
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null): void {
        super.onBeginContact(selfCollider, otherCollider, contact);
        if (otherCollider.group == 1 << 13) {
            if (this.graphics != otherCollider.getComponent(Graphics)) this.graphics = otherCollider.getComponent(Graphics);
        }
    }

    onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null): void {
        super.onEndContact(selfCollider, otherCollider, contact);
        if (otherCollider.group == 1 << 13) {
            if (this.graphics == otherCollider.getComponent(Graphics)) this.graphics = null;
        }
    }

}


